﻿using System;
using PH.Model.Achievements;
using PH.Logic.Commons;
using PH.Logic.Standards;
using PH.Data.Statistics;

namespace PH.Logic.Achievements
{
    public class MarkLogic
    {
        public static Guid ImportMark(Guid fileGuid, Guid archiveguid, Guid schoolGuid)
        {
            var workbook = FileLogic.GetExcel2003(fileGuid);
            Aspose.Cells.Cells cells = workbook.Worksheets[0].Cells;
            cells.DeleteBlankColumns();
            cells.DeleteBlankRows();
            var nc = cells.MaxDataColumn + 1;
            cells[0, nc].PutValue("错误信息");

            var subjects = SubjectLogic.GetSubjects(null);
            var teachers = PH.Logic.Schools.TeacherLogic.GetTeachers(new Model.Schools.TeacherQuery() { SchoolGuid = schoolGuid });
            var i = 1;
            var rows = cells.Rows.Count - 1;
            var nowrow = 0;
            FileLogic.UpdateFile(fileGuid, 0, rows);
            while (i < cells.Rows.Count)
            {
                try
                {
                    nowrow++;
                    FileLogic.UpdateFile(fileGuid, nowrow);

                    var model = new MarkModel();
                    model.ArchiveGuid = archiveguid;
                    model.SchoolGuid = schoolGuid;
                    if (cells[i, 0].Value == null) throw new Utils.PhException("请提供学生的身份证号。");
                    model.StudentNo = cells[i, 0].Value.ToString();
                    if (cells[i, 8].Value == null) throw new Utils.PhException("请提供学生姓名。");
                    model.StudentName = cells[i, 8].Value.ToString();
                    
                    if (cells[i, 2].Value == null)
                        model.TestMethod = 1;
                    else
                        model.TestMethod = (byte)(cells[i, 2].Value.ToString().Trim() == "2" ? 2 : 1);

                    if (cells[i, 1].Value == null) throw new Utils.PhException("请提供体育老师姓名。");
                    var teacher = teachers.Find(p => p.RealName == cells[i, 1].Value.ToString().Trim());
                    if (teacher != null) 
                        model.TeacherID = teacher.ID;
                    else
                        throw new Utils.PhException("体育老师不存在。");

                    #region 身高与体重
                    if (cells[i, 12].Value == null || cells[i, 13].Value == null)
                        throw new Utils.PhException("身高或体重没有数据");
                    var height=decimal.Parse(cells[i, 12].Value.ToString());
                    var weight=decimal.Parse(cells[i, 13].Value.ToString());
                    model.Achievement = weight / (height * height / 10000);
                    var bmi = subjects.Find(p => p.Category == 1);
                    model.Subject = bmi;
                    model.SubjectID = model.Subject.ID;
                    #endregion

                    var models = new MarkCollection();
                    models.Add(model);
                    for (var j = 14; j < nc; j++)
                    {
                        var sub = subjects.Find(p => p.SubjectName == (string)cells[0, j].Value);
                        if (sub == null)
                            throw new Utils.PhException(string.Format("没有相关项目（{0}）", (string)cells[0, j].Value));

                        if (cells[i, j].Value != null)
                        {
                            var v = cells[i, j].Value.ToString().Trim();
                            if (!string.IsNullOrEmpty(v))
                            {
                                decimal mark = 0;
                                bool autoPass = false;

                                if (v.ToUpper() != "M")
                                {
                                    if (sub.Category == 3)
                                    {
                                        v = System.Text.RegularExpressions.Regex.Replace(v, @"['`‘′’]", ".");
                                        v = System.Text.RegularExpressions.Regex.Replace(v, "[ “\"″]", "");
                                        var index = v.IndexOf(".");
                                        if (index > 0)
                                        {
                                            var minute = decimal.Parse(v.Substring(0, index).Trim());
                                            decimal second = 0;
                                            if (!string.IsNullOrEmpty(v.Substring(2).Trim()))
                                                second = decimal.Parse(v.Substring(2).Trim());
                                            mark = minute * 60 + second;
                                        }
                                        else
                                            mark = decimal.Parse(v);
                                    }
                                    else
                                        mark = decimal.Parse(v);
                                }
                                else
                                    autoPass = true;
                                
                                models.Add(new MarkModel()
                                {
                                    ArchiveGuid = archiveguid,
                                    SchoolGuid = schoolGuid,
                                    StudentNo = model.StudentNo,
                                    StudentName = model.StudentName,
                                    Subject = sub,
                                    SubjectID = sub.ID,
                                    Achievement = mark,
                                    TeacherID =model.TeacherID,
                                    TestMethod = model.TestMethod,
                                    AutoPass=autoPass
                                });
                            }
                        }
                    }
                    MarkCommand.CreateMarks(models);
                    cells.DeleteRow(i);
                }
                catch (Exception ex)
                {
                    if (ex.InnerException != null)
                        cells[i, nc].PutValue(ex.InnerException.Message);
                    else
                        cells[i, nc].PutValue(ex.Message);
                    i++;
                }
            }

            if (cells.Rows.Count > 1)
            {
                var errFile = FileLogic.SaveExcel2003ToFile(workbook, "导入成绩错误的记录.xls");
                return errFile.Guid;
            }
            return Guid.Empty;
        }

        public static MarkCollection Gets(MarkQuery sea)
        {
            return MarkCommand.Gets(sea);
        }

        public static void Update(int id, string newmark)
        {

            MarkCommand.Update(id, newmark);
        }

        public static MarkModel GetModel(int id)
        {
            return MarkCommand.GetModel(id);
        }

        public static void CopyMarks(Guid sGuid, Guid tGuid, Guid schGuid)
        {
            MarkCommand.CopyMarks(sGuid, tGuid, schGuid);
        }
    }
}
